/**
 * 获取当前页面查询参数
 * @param variable
 * @returns {string|boolean}
 */
function getQueryVariable(variable) {
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}


/**
 * 抹除当前页面查询参数
 * @param variable
 * @returns {string|boolean}
 */
function removeQueryVariable(variable) {
  let resultUrl = window.location.href.split("?")[0];
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  if (query.indexOf(variable + "=") == -1) {
    return window.location.href;
  }
  // 考虑了要移除的
  if (vars.length > 1) {
    resultUrl += "?";
  }
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] !== variable) {
      resultUrl += vars[i];
      if (i != vars.length - 1) {
        resultUrl += "&";
      }
    }
  }
  return resultUrl;
}

const Base64 = window.BASE64;

function getSubSystemFromToken(token): SSO.SystemInfo {
  let base64 = Base64.urlsafe_decode(token.split(".")[1]); // eslint-disable-line
  let subjectStr = JSON.parse(base64).sub;
  let subject = JSON.parse(subjectStr);
  return subject.ssochildSystemInfos.childSystemInfos.values;
}

// 用于SSO单点登录检验与跳转
import Storage from "@/framework/utils/Storage";
import { ACCESS_TOKEN_KEY, SSO_SUB_SYSTEMS_KEY } from "@/framework/enums/cacheEnum";

const jwt = getQueryVariable("jwt");
if (jwt) {
  Storage.set(ACCESS_TOKEN_KEY, jwt);
  Storage.set(SSO_SUB_SYSTEMS_KEY,getSubSystemFromToken(jwt));
  window.location.replace(removeQueryVariable("jwt"));
}
